package StudyCode.summary.zipfile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ZipDirectoryToZipOutputStream {
	public static void zipDir(String baseDir, String dir2zip,
	                          ZipOutputStream zos) throws IOException {

		File zipDir = new File(dir2zip);
		String[] dirList = zipDir.list();
		byte[] readBuffer = new byte[2156];
		int bytesIn = 0;
		for (int i = 0; i < dirList.length; i++) {
			File f = new File(zipDir, dirList[i]);
			if (f.isDirectory()) {
				String filePath = f.getPath();
				zipDir(baseDir, filePath, zos);
				continue;
			}
			FileInputStream fis = new FileInputStream(f);
			ZipEntry anEntry = new ZipEntry(subtractPath(baseDir,
					f.getPath()).replace("\\", "/"));

			zos.putNextEntry(anEntry);
			while ((bytesIn = fis.read(readBuffer)) != -1) {
				zos.write(readBuffer, 0, bytesIn);
			}
			fis.close();
		}
	}

	public static String subtractPath(String base, String full) {
		return full.substring(base.length() + 1);
	}
}
